/**
 * @file BT.c
 * @brief bluetooth Interface
 *
 * @version Fixed
 * @author lbx
 * @date 2015-04-28
 */
#include <sys/ioctl.h>
#include <sys/types.h>
#include <sys/err.h>
#include <fcntl.h>
#include <device.h>

int bt_get_status(void)
{
    int bt_fd = -1;
    
    bt_fd = open(CONFIG_BT_DEV, O_RDWR|O_NONBLOCK);
    return ioctl(bt_fd, IOCTL_BT_GET_STATUS, NULL); 
}

int bt_adv(uint32_t sec)
{
    int bt_fd = -1;
    
    bt_fd = open(CONFIG_BT_DEV, O_RDWR|O_NONBLOCK);
    return ioctl(bt_fd, IOCTL_BT_ADV, sec); 
}

int bt_disconnect(void)
{
    int bt_fd = -1;
    
    bt_fd = open(CONFIG_BT_DEV, O_RDWR|O_NONBLOCK);
    return ioctl(bt_fd, IOCTL_BT_DISCONNECT, NULL); 
}

int bt_set_name(const char *name, uint32_t len)
{
    int bt_fd = -1;
    bt_name_t param;

    param.name = name;
    param.len = len;
    bt_fd = open(CONFIG_BT_DEV, O_RDWR|O_NONBLOCK);
    return ioctl(bt_fd, IOCTL_BT_SET_NAME, &param);
}

int bt_get_name(const char *name, uint32_t len)
{
    int bt_fd = -1;
    bt_name_t param;

    param.name= name;
    param.len = len;
    bt_fd = open(CONFIG_BT_DEV, O_RDWR|O_NONBLOCK);
    return ioctl(bt_fd, IOCTL_BT_GET_NAME, &param);
}

int bt_get_addr(uint8_t addr[6])
{
    int bt_fd = -1;
    
    bt_fd = open(CONFIG_BT_DEV, O_RDWR|O_NONBLOCK);
    return ioctl(bt_fd, IOCTL_BT_GET_ADDR, addr);
}

int bt_read(uint8_t * buffer, size_t len, int timeout)
{
    int bt_fd = -1;
    bt_read_param_t param;

    param.buf = buffer;
    param.len = len;
    param.timeout = timeout;
    bt_fd = open(CONFIG_BT_DEV, O_RDWR|O_NONBLOCK);
    return ioctl(bt_fd, IOCTL_BT_READ, &param);
}

int bt_write(uint8_t * buffer, size_t len)
{
    int bt_fd = -1;
    bt_write_param_t param;

    param.buf = buffer;
    param.len = len;
    bt_fd = open(CONFIG_BT_DEV, O_RDWR|O_NONBLOCK);
    return ioctl(bt_fd, IOCTL_BT_WRITE, &param);
}

int bt_clrbuf(int rx, int tx)
{
    int bt_fd = -1;
    
    bt_fd = open(CONFIG_BT_DEV, O_RDWR|O_NONBLOCK);
    
    if (rx)
        return ioctl(bt_fd, IOCTL_BT_CLR_RXBUF, NULL);
    else if (tx)
        return ioctl(bt_fd, IOCTL_BT_CLR_TXBUF, NULL);

    return 0;
}

int bt_set_mode(uint32_t mode)
{
    int bt_fd = -1;
    
    bt_fd = open(CONFIG_BT_DEV, O_RDWR|O_NONBLOCK);
    return ioctl(bt_fd, IOCTL_BT_MODE_CTL, mode);
}
